<template>
  <view class="inventory-detail-container">
    <view class="page-header">
      <text class="page-title">库存详情</text>
    </view>

    <view v-if="loading" class="loading-container">
      <text>加载中...</text>
    </view>

    <view v-else class="detail-container">
      <view class="detail-section">
        <text class="section-title">基本信息</text>
        
        <view class="detail-item">
          <text class="detail-label">物品编码：</text>
          <view class="detail-value-wrapper">
            <text class="detail-value">{{ inventory.item_code || '-' }}</text>
            <text v-if="inventory.is_controlled" class="controlled-badge">管控物品</text>
          </view>
        </view>

        <view class="detail-item">
          <text class="detail-label">物品名称：</text>
          <text class="detail-value">{{ inventory.item_name || '-' }}</text>
        </view>

        <view class="detail-item">
          <text class="detail-label">物品类型：</text>
          <text class="type-badge" :class="'type-' + inventory.item_type">{{ getItemTypeText(inventory.item_type) }}</text>
        </view>

        <view class="detail-item">
          <text class="detail-label">分类：</text>
          <text class="detail-value">{{ inventory.category || '-' }}</text>
        </view>

        <view class="detail-item">
          <text class="detail-label">规格型号：</text>
          <text class="detail-value">{{ inventory.specification || '-' }}</text>
        </view>

        <view class="detail-item">
          <text class="detail-label">单位：</text>
          <text class="detail-value">{{ inventory.unit || '-' }}</text>
        </view>
      </view>

      <view class="detail-section">
        <text class="section-title">库存信息</text>
        
        <view class="detail-item">
          <text class="detail-label">当前库存：</text>
          <text class="detail-value quantity-value" :class="getQuantityClass()">{{ inventory.current_quantity || 0 }} {{ inventory.unit || '' }}</text>
        </view>

        <view class="detail-item">
          <text class="detail-label">最低库存：</text>
          <text class="detail-value">{{ inventory.min_quantity || 0 }}</text>
        </view>

        <view class="detail-item">
          <text class="detail-label">最大库存：</text>
          <text class="detail-value">{{ inventory.max_quantity || 0 }}</text>
        </view>

        <view class="detail-item">
          <text class="detail-label">单价：</text>
          <text class="detail-value">¥{{ inventory.unit_price || 0 }}</text>
        </view>

        <view class="detail-item">
          <text class="detail-label">存放位置：</text>
          <text class="detail-value">{{ inventory.storage_location || '-' }}</text>
        </view>

        <view class="detail-item">
          <text class="detail-label">状态：</text>
          <text class="status-badge" :class="'status-' + getStatusClass()">{{ getStatusText() }}</text>
        </view>
      </view>

      <view class="detail-section">
        <text class="section-title">供应商信息</text>
        
        <view class="detail-item">
          <text class="detail-label">供应商：</text>
          <text class="detail-value">{{ inventory.supplier || '-' }}</text>
        </view>

        <view class="detail-item">
          <text class="detail-label">生产厂家：</text>
          <text class="detail-value">{{ inventory.manufacturer || '-' }}</text>
        </view>

        <view class="detail-item">
          <text class="detail-label">批次号：</text>
          <text class="detail-value">{{ inventory.batch_no || '-' }}</text>
        </view>

        <view class="detail-item">
          <text class="detail-label">过期日期：</text>
          <view class="detail-value-wrapper">
            <text class="detail-value" :class="getExpiryClass()">{{ formatDate(inventory.expiry_date) }}</text>
            <text v-if="isExpiringSoon()" class="expiry-warning">即将过期</text>
          </view>
        </view>
      </view>

      <view class="detail-section">
        <text class="section-title">其他信息</text>
        
        <view class="detail-item">
          <text class="detail-label">条形码：</text>
          <text class="detail-value">{{ inventory.barcode || '-' }}</text>
        </view>

        <view class="detail-item">
          <text class="detail-label">二维码：</text>
          <text class="detail-value">{{ inventory.qrcode || '-' }}</text>
        </view>

        <view class="detail-item">
          <text class="detail-label">描述：</text>
          <text class="detail-value">{{ inventory.description || '-' }}</text>
        </view>

        <view class="detail-item">
          <text class="detail-label">使用说明：</text>
          <text class="detail-value">{{ inventory.usage_note || '-' }}</text>
        </view>

        <view class="detail-item">
          <text class="detail-label">最后采购日期：</text>
          <text class="detail-value">{{ formatDate(inventory.last_purchase_date) }}</text>
        </view>

        <view class="detail-item">
          <text class="detail-label">最后领用日期：</text>
          <text class="detail-value">{{ formatDate(inventory.last_issue_date) }}</text>
        </view>

        <view class="detail-item">
          <text class="detail-label">创建时间：</text>
          <text class="detail-value">{{ formatDate(inventory.create_time) }}</text>
        </view>

        <view class="detail-item">
          <text class="detail-label">更新时间：</text>
          <text class="detail-value">{{ formatDate(inventory.update_time) }}</text>
        </view>
      </view>

      <view class="detail-actions">
        <button class="btn-edit" @click="navigateToEdit">编辑</button>
        <button class="btn-delete" @click="handleDelete">删除</button>
        <button class="btn-back" @click="handleBack">返回</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'

const inventoryObj = uniCloud.importObject('dh-inventory')

const loading = ref(true)
const inventoryId = ref('')
const inventory = reactive({
  item_code: '',
  item_name: '',
  item_type: 4,
  category: '',
  specification: '',
  unit: '',
  current_quantity: 0,
  min_quantity: 0,
  max_quantity: 0,
  unit_price: 0,
  supplier: '',
  manufacturer: '',
  storage_location: '',
  batch_no: '',
  expiry_date: null,
  barcode: '',
  qrcode: '',
  description: '',
  usage_note: '',
  is_controlled: false,
  status: 1,
  last_purchase_date: null,
  last_issue_date: null,
  create_time: null,
  update_time: null
})

onMounted(() => {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  inventoryId.value = currentPage.options.id || ''
  
  if (inventoryId.value) {
    loadData()
  }
})

async function loadData() {
  loading.value = true
  try {
    const result = await inventoryObj.getInventoryById(inventoryId.value)
    if (result.code === 200 && result.data) {
      Object.assign(inventory, result.data)
    } else {
      uni.showToast({ title: result.message || '加载失败', icon: 'none' })
    }
  } catch (err) {
    console.error('加载失败:', err)
    uni.showToast({ title: err.message || '加载失败', icon: 'none' })
  } finally {
    loading.value = false
  }
}

function getItemTypeText(type) {
  const typeMap = { 1: '药品', 2: '医疗器械', 3: '耗材', 4: '其他' }
  return typeMap[type] || '未知'
}

function getStatusClass() {
  if (inventory.status === 4) return 'disabled'
  if (inventory.current_quantity === 0) return 'out'
  if (inventory.current_quantity <= inventory.min_quantity) return 'warning'
  return 'normal'
}

function getStatusText() {
  if (inventory.status === 4) return '停用'
  if (inventory.current_quantity === 0) return '缺货'
  if (inventory.current_quantity <= inventory.min_quantity) return '预警'
  return '正常'
}

function getQuantityClass() {
  if (inventory.current_quantity === 0) return 'quantity-out'
  if (inventory.current_quantity <= inventory.min_quantity) return 'quantity-low'
  return ''
}

function getExpiryClass() {
  if (!inventory.expiry_date) return ''
  const now = Date.now()
  const expiryDate = inventory.expiry_date
  if (expiryDate <= now) return 'expired'
  const daysUntilExpiry = (expiryDate - now) / (1000 * 60 * 60 * 24)
  if (daysUntilExpiry <= 30) return 'expiring-soon'
  return ''
}

function isExpiringSoon() {
  if (!inventory.expiry_date) return false
  const now = Date.now()
  const expiryDate = inventory.expiry_date
  const daysUntilExpiry = (expiryDate - now) / (1000 * 60 * 60 * 24)
  return daysUntilExpiry > 0 && daysUntilExpiry <= 30
}

function formatDate(timestamp) {
  if (!timestamp) return '-'
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

function navigateToEdit() {
  uni.navigateTo({ url: `/pages/business/inventory/edit?id=${inventoryId.value}` })
}

async function handleDelete() {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除此库存物品吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          const result = await inventoryObj.deleteInventory(inventoryId.value)
          if (result.code === 200) {
            uni.showToast({ title: '删除成功', icon: 'success' })
            setTimeout(() => {
              uni.navigateBack()
            }, 1500)
          } else {
            uni.showToast({ title: result.message || '删除失败', icon: 'none' })
          }
        } catch (err) {
          console.error('删除失败:', err)
          uni.showToast({ title: err.message || '删除失败', icon: 'none' })
        }
      }
    }
  })
}

function handleBack() {
  uni.navigateBack()
}
</script>

<style lang="scss" scoped>
.inventory-detail-container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  padding: 20rpx;
  background-color: #fff;
  border-radius: 10rpx;
  margin-bottom: 20rpx;
}

.page-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 100rpx;
  background-color: #fff;
  border-radius: 10rpx;
  font-size: 28rpx;
  color: #6b7280;
}

.detail-container {
  background-color: #fff;
  border-radius: 10rpx;
  padding: 30rpx;
}

.detail-section {
  margin-bottom: 40rpx;
  padding-bottom: 30rpx;
  border-bottom: 1px solid #e5e7eb;
  
  &:last-of-type {
    border-bottom: none;
  }
}

.section-title {
  display: block;
  font-size: 30rpx;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 20rpx;
  padding-left: 10rpx;
  border-left: 4px solid #3b82f6;
}

.detail-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 25rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.detail-label {
  flex-shrink: 0;
  width: 200rpx;
  font-size: 28rpx;
  color: #6b7280;
  font-weight: 500;
}

.detail-value {
  flex: 1;
  font-size: 28rpx;
  color: #1f2937;
  word-break: break-all;
  
  &.expired {
    color: #dc2626;
    font-weight: 600;
  }
  
  &.expiring-soon {
    color: #f59e0b;
    font-weight: 600;
  }
}

.detail-value-wrapper {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 10rpx;
  flex-wrap: wrap;
}

.controlled-badge {
  display: inline-block;
  padding: 4rpx 12rpx;
  border-radius: 6rpx;
  font-size: 20rpx;
  background-color: #fca5a5;
  color: #7f1d1d;
  font-weight: 600;
}

.expiry-warning {
  display: inline-block;
  padding: 4rpx 12rpx;
  border-radius: 6rpx;
  font-size: 20rpx;
  background-color: #fef3c7;
  color: #92400e;
  font-weight: 600;
}

.type-badge {
  display: inline-block;
  padding: 8rpx 20rpx;
  border-radius: 8rpx;
  font-size: 24rpx;
  font-weight: 600;
  
  &.type-1 { background-color: #dbeafe; color: #1e40af; }
  &.type-2 { background-color: #e0e7ff; color: #3730a3; }
  &.type-3 { background-color: #fef3c7; color: #92400e; }
  &.type-4 { background-color: #e5e7eb; color: #374151; }
}

.quantity-value {
  font-weight: 600;
  font-size: 32rpx;
  
  &.quantity-out { color: #dc2626; }
  &.quantity-low { color: #f59e0b; }
}

.status-badge {
  display: inline-block;
  padding: 8rpx 20rpx;
  border-radius: 8rpx;
  font-size: 24rpx;
  font-weight: 600;
  
  &.status-normal { background-color: #d1fae5; color: #065f46; }
  &.status-warning { background-color: #fef3c7; color: #92400e; }
  &.status-out { background-color: #fee2e2; color: #991b1b; }
  &.status-disabled { background-color: #e5e7eb; color: #6b7280; }
}

.detail-actions {
  display: flex;
  gap: 20rpx;
  margin-top: 50rpx;
}

.btn-edit, .btn-delete, .btn-back {
  flex: 1;
  padding: 25rpx;
  border-radius: 8rpx;
  font-size: 32rpx;
  border: none;
  cursor: pointer;
  text-align: center;
}

.btn-edit {
  background-color: #fbbf24;
  color: #fff;
}

.btn-delete {
  background-color: #ef4444;
  color: #fff;
}

.btn-back {
  background-color: #6c757d;
  color: #fff;
}
</style>

